<template>
  <a-collapse expandIconPosition="right">
    <a-collapse-panel header="配置设置" :force-render="true">
      <BasicForm @register="registerForm">
        <template v-for="item in limitNameList" :key="item" #[item]>
          <ShowInfo :index="item" :data="showInfoData" @merge-data="handleMerge" />
        </template>
      </BasicForm>
    </a-collapse-panel>
  </a-collapse>
</template>

<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form';
  import { modalFormStyleSetting } from '/@/settings/thingsBoardDesign';
  import { schemas, limitNameList } from './setting.data';
  import { Collapse as ACollapse, CollapsePanel as ACollapsePanel } from 'ant-design-vue';
  import ShowInfo from './components/ShowInfo.vue';
  import { watch, ref } from 'vue';
  import { deepMerge } from '/@/utils';
  import { useMessage } from '/@/hooks/web/useMessage';
  const props = defineProps({
    okFlag: { type: Boolean },
    editSetting: { type: Object },
  });

  const emits = defineEmits(['collectSettingData']);
  const settingData = ref<object>({
    tenantServerRestLimitsConfiguration: '',
    customerServerRestLimitsConfiguration: '',
    wsUpdatesPerSessionRateLimit: '',
    cassandraQueryTenantRateLimitsConfiguration: '',
    type: 'DEFAULT',
  });
  const showInfoData = ref<object>({});
  const { createMessage } = useMessage();
  watch(
    () => props.okFlag,
    async () => {
      try {
        const values = await validate();
        const res = deepMerge(values, settingData.value);
        emits('collectSettingData', 'success', res);
      } catch (error) {
        emits('collectSettingData', 'error');
        createMessage.warning('请检查 设备配置 表单填写是否正确');
      }
    },
    {
      immediate: false,
    },
  );
  const [registerForm, { validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    schemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  watch(
    () => props.editSetting,
    (nVal: object) => {
      setFieldsValue({ ...nVal });
      limitNameList.forEach((item) => {
        showInfoData.value[item] = nVal[item];
      });
    },
    {
      immediate: false,
      deep: true,
    },
  );
  function processingData(index: string, data: Array<object>) {
    let str = '';
    data.forEach((item: any, index, arr) => {
      str +=
        index == arr.length - 1
          ? item.msgCount + ':' + item.perSecond
          : item.msgCount + ':' + item.perSecond + ',';
    });
    settingData.value[index] = str;
  }

  function handleMerge(index: string, data: Array<object>) {
    processingData(index, data);
  }
</script>
